package shenxg.game;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class ItemGroup implements Comparable<ItemGroup> {
	public ArrayList<Item> items = new ArrayList<Item>();
	public final ColorType colorType;
	public final Scene scene;

	public ItemGroup(Scene scene, ColorType colorType) {
		this.colorType = colorType;
		this.scene = scene;
	}

	public boolean equals(Object o) {
		ItemGroup group = null;
		if (!(o instanceof ItemGroup)) {
			return false;
		}
		group = (ItemGroup) o;

		if (this.items.size() != group.items.size() || this.colorType != group.colorType) {
			return false;
		}

		for (int i = 0; i < items.size(); i++) {
			if(this.items.get(i).getX() != group.items.get(i).getX() || this.items.get(i).getY() != group.items.get(i).getY()){
				return false;
			}
		}

		return true;
	}

	public boolean addItem(Item item) throws Exception {
		if (item.getColorType() != this.colorType) {
			throw new Exception("Error ColorType !!!");
		}

		for (Item temp : items) {
			if (item.getX() == temp.getX() && temp.getY() == item.getY()) {
				return false;
			}
		}

		items.add(item);
		return true;
	}

	public int getScore() {
		int size = this.items.size();
		return size * size * 5;
	}

	public Scene destroy() throws Exception {
		Scene scene = new Scene(this.scene, this);
		for (Item item : items) {
			scene.items[item.getX()][item.getY()] = null;
			// System.out.println("destory : X : " + item.getX() + " Y : "+
			// item.getY());
		}
		scene.reInitAfterItemGroupDestory();
		scene.addScoreNow(this.getScore());

		if (scene.isFinal()) {
			if (null == scene.bestFinalScene) {
				scene.bestFinalScene = scene;
				// ScenePrint.printSceneAndParents(scene);
			} else if (scene.bestFinalScene.getFinalScore() < scene.getFinalScore()) {
				scene.bestFinalScene = scene;
				ScenePrint.printSceneAndParents(scene);
			}
		}

		//Collections.reverse(scene.getItemGroups());
		Collections.sort(scene.getItemGroups());
		return scene;
	}

	// just compare The Size
	public int compareTo(ItemGroup o) {
		int temp =  GameStart.random.nextInt() % 3 - 1;
		return temp * (this.items.size() - o.items.size());
	}
}
